<?php

/**
 * Talis Aspire Lists block
 *
 * @package     block
 * @subpackage  aspirelists
 * @copyright   2010 Talis Education Limited
 * @copyright   2011 Lancaster University Network Services Limited
 * @license     http://www.gnu.org/licenses/lgpl.html GNU LGPL
 * @author      Andrew Nicols <andrew.nicols@luns.net.uk>
 */

defined('MOODLE_INTERNAL') || die;

/**
 * The Talis Aspire List Block
 */
class block_aspirelists extends block_base {

    /**
     * Initialise the block
     *
     * This should set the title
     *
     * @return void
     */
    function init() {
        $this->title = get_string('aspirelists', 'block_aspirelists');
    }

    /**
     * Build and retrieve the contents of the block
     *
     * If the block is not configured, or the URL of the aspire server has
     * not been set, or the course has no idnumber set, then no content is
     * returned.
     *
     * Data is built by {@see get_data}
     *
     * @return stdClass
     */
    function get_content() {
        if ($this->content !== NULL) {
            return $this->content;
        }

        $this->content = new stdClass;

        // We only operate on courses with an idnumber
        if (empty($this->page->course->idnumber)) {
            return $this->content;
        }

        if (!$this->config = get_config('blocks/aspirelists')) {
            // The block has not been configured
            return $this->content;
        }

        if (empty($this->config->targetaspire)) {
            // No server has been set
            return $this->content;
        }

        // Retrieve the data
        $lists = $this->get_data();

        if (count($lists) == 0) {
            // No lists were found
            return $this->content;
        }

        // Render the data
        $renderer = $this->page->get_renderer('block_aspirelists');
        $this->content->text = $renderer->block_display($lists);

        return $this->content;
    }

    /**
     * Retrieve the data from the Aspire server
     *
     * @return array of stdClass objects containing the list data
     */
    private function get_data() {
        $code = strtolower($this->page->course->idnumber);

        // Build the URL for the JSON request
        $codedata = $this->config->targetaspire . '/' . $this->config->knowledgegroup . '/' . $code;
        $url = $codedata . '/lists.json';

        $lists = array();
        $curl = new curl(array('cache' => 'true', 'module_cache' => 'block_aspirelists'));
        if ($response = $curl->get($url)) {
            $data = json_decode($response, true);
            if (isset($data[$codedata]) && isset($data[$codedata]['http://purl.org/vocab/resourcelist/schema#usesList'])) {
                // Some lists were returned
                foreach ($data[$codedata]['http://purl.org/vocab/resourcelist/schema#usesList'] as $usesList) {
                    $list = new stdClass();
                    $list->url = $usesList["value"];
                    $list->name = $data[$list->url]['http://rdfs.org/sioc/spec/name'][0]['value'];

                    // Determine last updated
                    if (isset($data[$list->url]['http://purl.org/vocab/resourcelist/schema#lastUpdated'])) {
                        date_default_timezone_set('Europe/London');

                        // Determine when this list was last updated
                        $list->lastupdated =
                                strtotime($data[$list->url]['http://purl.org/vocab/resourcelist/schema#lastUpdated'][0]['value']);
                        $list->lastupdatedstring = userdate($list->lastupdated);
                        $list->lastupdatedcontext = format_time(time() - $list->lastupdated);
                    }

                    // Determine the item count
                    $list->count = 0;
                    if (isset($data[$list->url]['http://purl.org/vocab/resourcelist/schema#contains'])) {
                        foreach ($data[$list->url]['http://purl.org/vocab/resourcelist/schema#contains'] as $things) {
                            if (preg_match('/\/items\//',$things['value'])) {
                                // Only increment the list count for items - lists can contain sections too
                                $list->count++;
                            }
                        }
                    }
                    $lists[$list->name] = $list;
                }
            }
        }

        // Sort the lists by name
        $keys = array_map(create_function('$a', 'return strtolower($a->name);'), $lists);
        array_multisort($keys, SORT_ASC, SORT_STRING, $lists);

        return $lists;
    }

    function has_config() {
        return true;
    }

    function applicable_formats() {
        return array('course-view' => true);
    }
}
